package com.browser;

import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;

import org.json.JSONObject;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;

/**
 * Created by mincj on 2016/11/1.
 */

public class DrawPath implements DrawProtocol{
    private ArrayList<PointF> sets = new ArrayList<>();

    public static final PointF Point2Rate(PointF pt, PointF sz){
        return new PointF(pt.x/sz.x, pt.y/sz.y);
    }
    public static final PointF Rate2Point(PointF pt, PointF sz){
        return new PointF(pt.x * sz.x, pt.y * sz.y);
    }

    public DrawPath(){

    }
    public DrawPath(PointF start){
        sets.add(start);
    }

    public void appendPoint(PointF pt){
        sets.add(pt);
    }

    public Path genPath(RectF rectF){
        Path path = new Path();
        for (int i = 0; i < sets.size(); i++){
            PointF point = Rate2Point(sets.get(i), new PointF(rectF.width(), rectF.height()));
            point = new PointF(point.x + rectF.left, point.y + rectF.top);
            if(i == 0){
                path.moveTo(point.x, point.y);
            }else{
                path.lineTo(point.x, point.y);
            }
        }
        return path;
    }


    public JSONObject toJson(){
        JSONObject object = new JSONObject();
        try {
            String x = new String();
            String y = new String();

            int i = 0;
            for (; i < sets.size(); i++){
                PointF item = sets.get(i);
                if(i == 0){
                    x = String.format( "%.9f", item.x);
                    y = String.format("%.9f", item.y);
                }else{
                    x = String.format("%s,%.9f", x, item.x);
                    y = String.format("%s,%.9f", y, item.y);
                }
            }

            object.put("type", 0x00);
            object.put("x", x);
            object.put("y", y);
        }catch (Exception e){

        }
        return object;
    }

    public void fromJson(JSONObject jsonObject){
        if(jsonObject == null) return;

        try {
            String x = jsonObject.getString("x");
            String y = jsonObject.getString("y");

            String xSets[] = x.split(",");
            String ySets[] = y.split(",");

            int count = Math.min(xSets.length, ySets.length);
            int i = 0;
            for (; i < count; i++){
                PointF pointF = new PointF();
                pointF.set(Float.valueOf(xSets[i]), Float.valueOf(ySets[i]));

                sets.add(pointF);
            }
        }catch (Exception e){

        }
    }

}
